﻿#include "nuf_bus_info.h"
#include "com_manager.h"
#include "gpio_info.h"

#include <QApplication>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <plug_info.h>
#include <topo_info.h>
com_manager* com_manager::mgr = NULL;
QMap<QString, rs232com*> com_manager::mapCom;
com_manager::com_manager() : QObject() {}
com_manager* com_manager::instance()
{
	if (mgr == NULL)
		mgr = new com_manager;
	return mgr;
}

void  com_manager::enum_com()
{
    QextSerialEnumerator* enumerator = new QextSerialEnumerator(this);
    enumerator->setUpNotifications();

	foreach(QextPortInfo info, QextSerialEnumerator::getPorts())
    {
        if (info.portName.isEmpty())
             continue;

       // if (info.friendName.contains("CH34" ))
        {
            comList.append(info.portName);
         }

	}
}

void com_manager::openCom(QString comName)
{

}

void com_manager::openAllCom()
{
    TopoInfo::Instance()->node_map.clear();

    foreach (QString comName, comList)
    {
        rs232com* rs232= get_com(comName);
        if (rs232 == nullptr )
            continue;

        QString  mac_id= rs232->query_mac_address();

        TOPO_NODE *node =   rs232->query_current_node_info();

      int cnt= rs232->query_node_count();

        if ( node)
        {
           // GpioSetting::init_gpio(comName);


            node-> mac_id=mac_id;
            node->comName = comName;

            //com_map[comName] = mac_id;

            for ( int i =0; i < 8; i ++ )
            {
                rs232-> query_gpio(i);
            }
        }
    }
    //TopoSetting::loadSetting();
    NufBusSetting::save_Bus_Setting();
    TopoInfo::Instance()->save_topo_setting();
    GpioSetting::save_gpio_setting();
    //QJsonArray arrayNet;


    // QJsonObject arrayMap;
    // QMap<QString, QString>::Iterator  it = com_map.begin();

    // while  (it !=  com_map.end())
    // {
    //     arrayMap[it.key()] = it.value();
    //     it ++;
    // }
    // QByteArray bytes = QJsonDocument(arrayMap).toJson();

    // QFile fileArray(QApplication::applicationDirPath() + "/data/com_info.json");
    // if (fileArray.open(QIODevice::WriteOnly))
    // {
    //     fileArray.write(bytes);
    //     fileArray.close();
    // }
}

rs232com* com_manager::get_com(QString portName)
{
    portName = portName .toUpper();
    if (mapCom.contains(portName))
        return mapCom[portName];

    rs232com* rs232 = new rs232com(portName);

    bool opened=  rs232->openPort(portName, BaudRateType::BAUD115200, DataBitsType::DATA_8, ParityType::PAR_NONE, StopBitsType::STOP_1);
    if (!opened)
        return NULL ;

    mapCom[portName] = rs232;
    return rs232;
}

void com_manager::close()
{
	QMap<QString, rs232com*>::Iterator it = mapCom.begin();

	while (it != mapCom.end())
	{
		it.value()->close_port();
		it++;
	}
}
